<?php

namespace app\admin\controller\qingdong\work;

use addons\qingdong\model\Customer;
use addons\qingdong\model\Staff;
use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use addons\qingdong\model\Form;
use addons\qingdong\model\Flow as FlowModel;
use fast\Tree;

/**
 * 审批流程
 */
class Flow extends Backend {
    protected $relationSearch = true;
    protected $searchFields = 'id,name';
    /**
     * @var \addons\qingdong\model\Flow
     */
	protected $model = null;


	public function _initialize() {
		parent::_initialize();
		$this->model = new FlowModel();


        $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());
        //角色组
        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        $this->view->assign('groupdata', $groupdata);
	}


	/**
	 * 查看
	 */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $forms = $this->model->where([])->select();
            $forms = collection($forms)->toArray();

            $result = array("total" => count($forms), "rows" => $forms);
            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 新增
     * @return string
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $row = $this->request->post('row/a');
            $findType = $this->model->where(array('relation_type'=>$row['relation_type']))->find();
            if($findType){
                $this->error('关联对象已存在,请在列表中进行修改');
            }
            if($row['status'] == 1){
                $examine_ids = json_decode($row['examine_ids'],true);
                if(!$examine_ids){
                    $this->error('请选择审批人');
                }
                foreach($examine_ids as $k=>$v){
                    if(!$v['staff_id']  && $v['stafftype'] !=3){
                        $this->error('请选择审批人');
                    }
                }
            }
            $data = [
                'name' => $row['name'],
                'relation_type' => $row['relation_type'],
                'status' => $row['status'],
                'examine_ids' => $row['examine_ids'],
                'remark' => $row['remark'],
                'group_ids' => implode(',',$row['group_ids']??[]),
                'last_modified'=>time(),
                'last_admin_id'=>$this->auth->id
            ];
            $result = $this->model->allowField(true)->save($data);
            if (!$result) {
                $this->error('提交失败');
            }
            $this->success('提交成功');
        }
        return $this->view->fetch();
    }


    /**
     * 修改
     * @return string
     */
	public function edit($ids = null) {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isAjax()) {
            $row = $this->request->post('row/a');

            if($row['status'] == 1){
                $examine_ids = json_decode($row['examine_ids'],true);
                if(!$examine_ids){
                    $this->error('请选择审批人');
                }
                foreach($examine_ids as $k=>$v){
                    if(!$v['staff_id'] && $v['stafftype'] !=3){
                        $this->error('请选择审批人');
                    }
                }
            }
            $result = $this->model::destroy(['id'=>$ids]);
            if (!$result) {
                $this->error('删除失败');
            }

            $data = [
                'name' => $row['name'],
                'relation_type' => $row['relation_type'],
                'status' => $row['status'],
                'examine_ids' => $row['examine_ids'],
                'remark' => $row['remark'],
                'group_ids' => implode(',',$row['group_ids']),
                'last_modified'=>time(),
                'last_admin_id'=>$this->auth->id
            ];
            $result = $this->model->allowField(true)->save($data);
            if (!$result) {
                $this->error(__('No rows were updated'));
            }
            $this->success();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
	}

    /**
     * 删除
     * @param null $ids
     * @return string|void
     */
    public function del($ids = null) {
        if ($this->request->isAjax()) {
            $map['id'] = $ids;
            $row=$this->model->get($ids);
            if(!$row){
                $this->error('数据不存在');
            }
            $result    = $this->model->destroy($map);
            if (!$result) {
                $this->error('删除失败');
            }
            $this->success('删除成功');
        }

        return $this->view->fetch();
    }


    /**
     * 员工列表
     */
    public function getstaff()
    {
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = ['in',explode(',',$keyValue)];
        }
        $name = input('name');
        if (!empty($name)) {
            $where['name'] = ['like', '%' . $name . '%'];
        }
        $customer = Staff::where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $customer->items(), 'total' => $customer->total()]);
    }
}
